package com.ruoyi.setlanguages.service;


import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.*;
import com.ruoyi.setlanguages.io.ChannelInfo;
import com.ruoyi.setlanguages.io.VideoInfo;
import com.ruoyi.setlanguages.until.YouTubeAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.*;

@Service
public class YouTubeManager {
    private  YouTube youtubeService;

    @Autowired
    public YouTubeManager(YouTube youtubeService) {
        this.youtubeService = youtubeService;
        System.out.println("YouTubeManager初始化完成");
        try {
            List<ChannelInfo> channels = getMyChannels();
            if (channels.isEmpty()) {
                System.out.println("未找到频道...");

            }
            String channel = "";
            for (int i = 0; i < channels.size(); i++) {
                System.out.println("[" + (i + 1) + "] " + channels.get(i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除凭证并重新初始化YouTube服务
     */
    public boolean clearAndReinitializeService() {
        try {
            System.out.println("开始清除凭证并重新初始化YouTube服务...");

            // 使用YouTubeAuth工具类清除并重新初始化
            YouTube newYouTubeService = YouTubeAuth.clearAndReinitialize();
            this.youtubeService = newYouTubeService;

            System.out.println("YouTube服务重新初始化成功");
            return true;

        } catch (IOException | GeneralSecurityException e) {
            System.err.println("重新初始化YouTube服务失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检查认证状态
     */
    public String getAuthStatus() {
        return YouTubeAuth.getAuthStatus();
    }

    /**
     * 刷新访问令牌
     */
    public boolean refreshToken() {
        try {
            return YouTubeAuth.refreshToken();
        } catch (IOException e) {
            System.err.println("刷新令牌失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 仅清除凭证但不重新初始化（用于切换账号前的清理）
     */
    public boolean clearCredentialsOnly() {
        try {
            YouTubeAuth.clearCredentials();
            this.youtubeService = null;
            System.out.println("凭证已清除，需要重新初始化服务");
            return true;
        } catch (IOException e) {
            System.err.println("清除凭证失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 强制重新初始化服务（在凭证清除后调用）
     */
    public boolean forceReinitialize() {
        try {
            YouTube newYouTubeService = YouTubeAuth.getYouTubeService();
            this.youtubeService = newYouTubeService;
            System.out.println("YouTube服务强制重新初始化成功");
            return true;
        } catch (IOException | GeneralSecurityException e) {
            System.err.println("强制重新初始化失败: " + e.getMessage());
            return false;
        }
    }

    // 确保在调用YouTube服务前检查服务是否可用
    private void checkServiceAvailable() throws IllegalStateException {
        if (youtubeService == null) {
            throw new IllegalStateException("YouTube服务未初始化，请先进行认证");
        }
    }


    // 获取用户的所有频道
    public List<ChannelInfo> getMyChannels() throws IOException {
        checkServiceAvailable();
        List<ChannelInfo> channels = new ArrayList<>();

        // 修复：使用字符串列表而不是单个字符串
        YouTube.Channels.List request = youtubeService.channels()
                .list("snippet,statistics,contentDetails");
        request.setMine(true);

        ChannelListResponse response = request.execute();

        for (Channel channel : response.getItems()) {
            ChannelInfo info = new ChannelInfo();
            info.setId(channel.getId());
            info.setTitle(channel.getSnippet().getTitle());
            info.setDescription(channel.getSnippet().getDescription());

            if (channel.getStatistics() != null) {
                info.setSubscriberCount(channel.getStatistics().getSubscriberCount().longValue());
                info.setVideoCount(channel.getStatistics().getVideoCount().longValue());
                info.setViewCount(channel.getStatistics().getViewCount().longValue());
            }

            info.setChannelUrl("https://www.youtube.com/channel/" + channel.getId());
            info.setPublishedAt(channel.getSnippet().getPublishedAt());

            channels.add(info);
        }

        return channels;
    }

    // 获取频道下的所有视频（包含版权状态和原始文件名）
    public List<VideoInfo> getChannelVideos(String channelId) throws IOException {
        checkServiceAvailable();
        List<VideoInfo> videos = new ArrayList<>();

        // 首先获取上传播放列表ID
        YouTube.Channels.List channelRequest = youtubeService.channels()
                .list("contentDetails");
        channelRequest.setId(channelId);

        ChannelListResponse channelResponse = channelRequest.execute();
        if (channelResponse.getItems().isEmpty()) {
            return videos;
        }

        String uploadsPlaylistId = channelResponse.getItems().get(0)
                .getContentDetails().getRelatedPlaylists().getUploads();

        // 获取播放列表中的视频
        YouTube.PlaylistItems.List playlistRequest = youtubeService.playlistItems()
                .list("snippet,contentDetails");
        playlistRequest.setPlaylistId(uploadsPlaylistId);
        playlistRequest.setMaxResults(50L);

        PlaylistItemListResponse playlistResponse = playlistRequest.execute();

        // 收集所有视频ID，用于批量获取详细信息
        List<String> videoIds = new ArrayList<>();
        Map<String, VideoInfo> videoInfoMap = new HashMap<>();

        for (PlaylistItem item : playlistResponse.getItems()) {
            String videoId = item.getContentDetails().getVideoId();
            videoIds.add(videoId);

            VideoInfo videoInfo = new VideoInfo();
            videoInfo.setId(videoId);
            videoInfo.setTitle(item.getSnippet().getTitle());
            videoInfo.setDescription(item.getSnippet().getDescription());
            videoInfo.setPublishedAt(item.getSnippet().getPublishedAt());

            videoInfoMap.put(videoId, videoInfo);
        }

        // 批量获取视频的详细信息（版权状态、原始文件名等）
        if (!videoIds.isEmpty()) {
            List<VideoInfo> detailedVideos = getVideosDetailedInfo(videoIds);
            for (VideoInfo detailedVideo : detailedVideos) {
                VideoInfo basicVideo = videoInfoMap.get(detailedVideo.getId());
                if (basicVideo != null) {
                    // 合并基本信息
                    basicVideo.setCopyrightStatus(detailedVideo.getCopyrightStatus());
                    basicVideo.setOriginalFilename(detailedVideo.getOriginalFilename());
                    basicVideo.setPrivacyStatus(detailedVideo.getPrivacyStatus());
                    basicVideo.setViewCount(detailedVideo.getViewCount());
                    basicVideo.setLikeCount(detailedVideo.getLikeCount());
                    basicVideo.setCommentCount(detailedVideo.getCommentCount());
                }
            }
        }

        videos.addAll(videoInfoMap.values());
        return videos;
    }

    // 批量获取视频的详细信息
    private List<VideoInfo> getVideosDetailedInfo(List<String> videoIds) throws IOException {
        checkServiceAvailable();
        List<VideoInfo> detailedVideos = new ArrayList<>();

        // 每次最多处理50个视频（API限制）
        for (int i = 0; i < videoIds.size(); i += 50) {
            int end = Math.min(i + 50, videoIds.size());
            List<String> batchIds = videoIds.subList(i, end);

            String vedioId = batchIds.get(0);
            YouTube.Videos.List videosRequest = youtubeService.videos()
                    .list("snippet,status,fileDetails,statistics");
            videosRequest.setId(vedioId);

            VideoListResponse response = videosRequest.execute();

            for (Video video : response.getItems()) {
                VideoInfo videoInfo = new VideoInfo();
                videoInfo.setId(video.getId());

                // 设置版权状态和隐私状态
                if (video.getStatus() != null) {
                    videoInfo.setPrivacyStatus(video.getStatus().getPrivacyStatus());
                    // 版权状态可能需要其他API或自定义逻辑
                    videoInfo.setCopyrightStatus(determineCopyrightStatus(video));
                }

                // 设置原始文件名
                if (video.getFileDetails() != null) {
                    videoInfo.setOriginalFilename(video.getFileDetails().getFileName());
                }

                // 设置统计数据
                if (video.getStatistics() != null) {
                    videoInfo.setViewCount(video.getStatistics().getViewCount().longValue());
                    videoInfo.setLikeCount(video.getStatistics().getLikeCount().longValue());
                    videoInfo.setCommentCount(video.getStatistics().getCommentCount().longValue());
                }

                detailedVideos.add(videoInfo);
            }
        }

        return detailedVideos;
    }

    // 确定版权状态（需要根据业务逻辑自定义）
    private String determineCopyrightStatus(Video video) {
        checkServiceAvailable();
        // 这里可以根据视频的各种属性来判断版权状态
        // 注意：YouTube API不直接提供版权状态，需要根据其他信息推断

        if (video.getStatus() != null) {
            String license = video.getStatus().getLicense();
            if ("creativeCommon".equals(license)) {
                return "知识共享";
            } else if ("youtube".equals(license)) {
                return "标准YouTube许可";
            }
        }

        // 检查是否有内容版权声明
        if (video.getContentDetails() != null) {
            ContentRating contentRating = video.getContentDetails().getContentRating();
            if (contentRating != null) {
                // 如果有内容评级，可能涉及版权
                return "受版权保护";
            }
        }

        return "版权状态未知";
    }

    // 获取单个视频的详细信息（包含版权状态和原始文件名）
    public VideoInfo getVideoDetails(String videoId) throws IOException {
        checkServiceAvailable();
        YouTube.Videos.List videoRequest = youtubeService.videos()
                .list("snippet,status,fileDetails,statistics,contentDetails");
        videoRequest.setId(videoId);

        VideoListResponse response = videoRequest.execute();
        if (response.getItems().isEmpty()) {
            throw new IllegalArgumentException("视频未找到: " + videoId);
        }

        Video video = response.getItems().get(0);
        VideoInfo videoInfo = new VideoInfo();
        videoInfo.setId(video.getId());
        videoInfo.setTitle(video.getSnippet().getTitle());
        videoInfo.setDescription(video.getSnippet().getDescription());
        videoInfo.setPublishedAt(video.getSnippet().getPublishedAt());

        // 设置版权状态和隐私状态
        if (video.getStatus() != null) {
            videoInfo.setPrivacyStatus(video.getStatus().getPrivacyStatus());
            videoInfo.setCopyrightStatus(determineCopyrightStatus(video));
        }

        // 设置原始文件名
        if (video.getFileDetails() != null) {
            videoInfo.setOriginalFilename(video.getFileDetails().getFileName());
        }

        // 设置统计数据
        if (video.getStatistics() != null) {
            videoInfo.setViewCount(video.getStatistics().getViewCount().longValue());
            videoInfo.setLikeCount(video.getStatistics().getLikeCount().longValue());
            videoInfo.setCommentCount(video.getStatistics().getCommentCount().longValue());
        }

        return videoInfo;
    }

    // 获取视频的版权信息（专门的方法）
    public Map<String, String> getVideoCopyrightInfo(String videoId) throws IOException {
        checkServiceAvailable();
        Map<String, String> copyrightInfo = new HashMap<>();

        YouTube.Videos.List videoRequest = youtubeService.videos()
                .list("status,fileDetails,contentDetails");
        videoRequest.setId( videoId);

        VideoListResponse response = videoRequest.execute();
        if (response.getItems().isEmpty()) {
            throw new IllegalArgumentException("视频未找到: " + videoId);
        }

        Video video = response.getItems().get(0);

        // 原始文件名
        if (video.getFileDetails() != null) {
            copyrightInfo.put("originalFilename", video.getFileDetails().getFileName());
        } else {
            copyrightInfo.put("originalFilename", "未知");
        }

        // 隐私状态
        if (video.getStatus() != null) {
            copyrightInfo.put("privacyStatus", video.getStatus().getPrivacyStatus());
            copyrightInfo.put("license", video.getStatus().getLicense());
        }

        // 版权状态
        copyrightInfo.put("copyrightStatus", determineCopyrightStatus(video));

        // 上传状态
        if (video.getStatus() != null) {
            copyrightInfo.put("uploadStatus", video.getStatus().getUploadStatus());
            copyrightInfo.put("embeddable", String.valueOf(video.getStatus().getEmbeddable()));
        }

        return copyrightInfo;
    }

    // 更新视频标题
    public void updateVideoTitle(String videoId, String newTitle) throws IOException {
        checkServiceAvailable();
        // 首先获取视频的当前信息
        YouTube.Videos.List videoRequest = youtubeService.videos()
                .list("snippet");
        videoRequest.setId(videoId);

        VideoListResponse response = videoRequest.execute();
        if (response.getItems().isEmpty()) {
            throw new IllegalArgumentException("视频未找到: " + videoId);
        }

        Video video = response.getItems().get(0);
        video.getSnippet().setTitle(newTitle);

        // 更新视频
        YouTube.Videos.Update updateRequest = youtubeService.videos()
                .update("snippet", video);
        updateRequest.execute();
        System.out.println("视频标题已更新为: " + newTitle);
    }

    // 根据视频ID添加多语言标题
    public void addMultiLanguageTitle(String videoId, Map<String, String> languageTitles) throws IOException {
        checkServiceAvailable();
        // 首先获取视频的当前信息
        YouTube.Videos.List videoRequest = youtubeService.videos()
                .list("snippet,localizations");
        videoRequest.setId(videoId);

        VideoListResponse response = videoRequest.execute();
        if (response.getItems().isEmpty()) {
            throw new IllegalArgumentException("视频未找到: " + videoId);
        }

        Video video = response.getItems().get(0);
        VideoSnippet snippet = video.getSnippet();

        // 设置默认标题（如果提供了英语标题）
        if (languageTitles.containsKey("en")) {
            snippet.setTitle(languageTitles.get("en"));
        }

        // 创建或更新本地化信息
        if (video.getLocalizations() == null) {
            video.setLocalizations(new HashMap<>());
        }

        for (Map.Entry<String, String> entry : languageTitles.entrySet()) {
            String languageCode = entry.getKey();
            String title = entry.getValue();

            VideoLocalization localization = new VideoLocalization();
            localization.setTitle(title);

            video.getLocalizations().put(languageCode, localization);
        }

        // 更新视频，包括snippet和localizations
        YouTube.Videos.Update updateRequest = youtubeService.videos()
                .update("snippet, localizations", video);
        updateRequest.execute();

        System.out.println("成功为视频 " + videoId + " 添加多语言标题:");
        for (Map.Entry<String, String> entry : languageTitles.entrySet()) {
            String languageName = getLanguageDisplayName(entry.getKey());
            System.out.println("  " + languageName + ": " + entry.getValue());
        }
    }

    // 为单个视频添加单个语言标题
    public void addSingleLanguageTitle(String videoId, String languageCode, String title) throws IOException {
        checkServiceAvailable();
        Map<String, String> languageTitles = new HashMap<>();
        languageTitles.put(languageCode, title);
        addMultiLanguageTitle(videoId, languageTitles);
    }

    // 获取视频的当前多语言标题信息
    public Map<String, String> getVideoLocalizations(String videoId) throws IOException {
        checkServiceAvailable();
        YouTube.Videos.List videoRequest = youtubeService.videos()
                .list("localizations");
        videoRequest.setId(videoId);

        VideoListResponse response = videoRequest.execute();
        if (response.getItems().isEmpty()) {
            throw new IllegalArgumentException("视频未找到: " + videoId);
        }

        Video video = response.getItems().get(0);
        Map<String, String> localizations = new HashMap<>();

        if (video.getLocalizations() != null) {
            for (Map.Entry<String, VideoLocalization> entry : video.getLocalizations().entrySet()) {
                localizations.put(entry.getKey(), entry.getValue().getTitle());
            }
        }

        return localizations;
    }

    // 获取语言显示名称
    private String getLanguageDisplayName(String languageCode) {
        Map<String, String> languages = getSupportedLanguages();
        return languages.getOrDefault(languageCode, languageCode);
    }

    // 获取支持的语言映射
    public static Map<String, String> getSupportedLanguages() {
        Map<String, String> languages = new LinkedHashMap<>();
        languages.put("ar", "阿拉伯语");
        languages.put("km", "高棉语");
        languages.put("fil", "菲律宾语");
        languages.put("en", "英语");
        languages.put("fr", "法语");
        languages.put("ms", "马来语");
        languages.put("ta", "泰米尔语");
        languages.put("ja", "日语");
        languages.put("ko", "韩语");
        languages.put("de", "德语");
        languages.put("th", "泰语");
        languages.put("it", "意大利语");
        languages.put("es", "西班牙语");
        languages.put("pt", "葡萄牙语");
        languages.put("vi", "越南语");
        languages.put("my", "缅甸语");
        languages.put("hi", "印地语");
        languages.put("id", "印度尼西亚语");
        languages.put("zh-CN", "简体中文");
        languages.put("zh-TW", "繁体中文");
        languages.put("ru", "俄语");
        return languages;
    }

    // 验证语言代码是否支持
    public static boolean isLanguageSupported(String languageCode) {
        return getSupportedLanguages().containsKey(languageCode);
    }

    // 获取视频详细信息（新增方法）
    public VideoInfo getVideoDetailsTwo(String videoId) throws IOException {
        YouTube.Videos.List videoRequest = youtubeService.videos()
                .list("snippet, statistics, contentDetails");
        videoRequest.setId(videoId);

        VideoListResponse response = videoRequest.execute();
        if (response.getItems().isEmpty()) {
            throw new IllegalArgumentException("视频未找到: " + videoId);
        }

        Video video = response.getItems().get(0);
        VideoInfo videoInfo = new VideoInfo();
        videoInfo.setId(video.getId());
        videoInfo.setTitle(video.getSnippet().getTitle());
        videoInfo.setDescription(video.getSnippet().getDescription());
        videoInfo.setPublishedAt(video.getSnippet().getPublishedAt());

        return videoInfo;
    }

    // 搜索视频（新增方法）
    public List<VideoInfo> searchVideos(String query, long maxResults) throws IOException {
        List<VideoInfo> videos = new ArrayList<>();

        YouTube.Search.List searchRequest = youtubeService.search()
                .list("snippet");
        searchRequest.setQ(query);
        searchRequest.setType("video");
        searchRequest.setMaxResults(maxResults);

        SearchListResponse response = searchRequest.execute();

        for (SearchResult result : response.getItems()) {
            VideoInfo videoInfo = new VideoInfo();
            videoInfo.setId(result.getId().getVideoId());
            videoInfo.setTitle(result.getSnippet().getTitle());
            videoInfo.setDescription(result.getSnippet().getDescription());
            videoInfo.setPublishedAt(result.getSnippet().getPublishedAt());

            videos.add(videoInfo);
        }

        return videos;
    }


}